/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;

import com.home.common.utils.DateUtils;
import com.home.logic.AttributeGroupLogic;
import com.home.logic.ReportLogic;
import com.home.logic.VentureLogic;
import com.home.mapping.AttributeGroup;
import com.home.mapping.ScorecardType;
import com.home.mapping.Venture;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.ImageIcon;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author pnduy
 */
public class InboundReport extends javax.swing.JInternalFrame {
    private ScorecardType scorecardType;
    /**
     * Creates new form InboundReport
     */
    public InboundReport(ScorecardType scorecardType) {
        initComponents();
        
        this.setTitle(scorecardType.getType() + " Report");
        
        int currentWeek = DateUtils.getCurrentWeekOfYear();
        List<Venture> ventures = new VentureLogic().findAllVenture();
        
        for (Venture v : ventures) {
            if (v.getVentureName().equals("Regional")) {
                ventures.remove(v);
                break;
            }
        }
        
        this.scorecardType = scorecardType;
        Integer type = scorecardType.getIdScorecardType();
        
        List<AttributeGroup> listAttrGroup = new AttributeGroupLogic().findAttrGroupByType(type);
        
        Map<String, Map<Integer, Double>> mapReportTotalScore = new ReportLogic().getMapDataForTotalScoreOfVentureInWeeks(currentWeek - 4, currentWeek - 1, ventures, type);
        
        int week = DateUtils.getCurrentWeekOfYear();
        Map<String, Double> mapReportAttributeGroup = new ReportLogic().getMapDataForGroupAttrScoreReport_Sinh(ventures, week - 1, type, listAttrGroup);
        
        final CategoryDataset totalScoreOfVentureInWeeksDs = createDatasetChart1(mapReportTotalScore);
        final JFreeChart chart = createChart(totalScoreOfVentureInWeeksDs);
        
        final CategoryDataset attrGroupScoreReportDs = createDatasetChart2(mapReportAttributeGroup, listAttrGroup, ventures);
        final JFreeChart chart2 = createChart2(attrGroupScoreReportDs);
        
        BufferedImage img1 = chart.createBufferedImage(560, 550);
        jLabel1.setIcon(new ImageIcon(img1));
        
        BufferedImage img2 = chart2.createBufferedImage(560, 550);
        jLabel2.setIcon(new ImageIcon(img2));
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        leftPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        rightPanel = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();

        setClosable(true);
        setTitle("Inbound Report");
        setPreferredSize(new java.awt.Dimension(1200, 600));

        jSplitPane1.setDividerLocation(600);

        javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
        leftPanel.setLayout(leftPanelLayout);
        leftPanelLayout.setHorizontalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(leftPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 579, Short.MAX_VALUE)
                .addContainerGap())
        );
        leftPanelLayout.setVerticalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(leftPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPane1.setLeftComponent(leftPanel);

        javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel);
        rightPanel.setLayout(rightPanelLayout);
        rightPanelLayout.setHorizontalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rightPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 558, Short.MAX_VALUE)
                .addContainerGap())
        );
        rightPanelLayout.setVerticalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rightPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 547, Short.MAX_VALUE)
                .addContainerGap())
        );

        jSplitPane1.setRightComponent(rightPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JPanel leftPanel;
    private javax.swing.JPanel rightPanel;
    // End of variables declaration//GEN-END:variables
    private CategoryDataset createDatasetChart1(Map<String, Map<Integer, Double>> mapValue) {
       
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();        
        for (String ventureName : mapValue.keySet()) {
            Map<Integer,Double> mapWeekAndValue = mapValue.get(ventureName);
            for (Integer week : mapWeekAndValue.keySet()) {
                Double value = mapWeekAndValue.get(week);
                dataset.addValue(value, ventureName, "week "+week);
            }
        }
        
        return dataset;
                
    }
    
    private CategoryDataset createDatasetChart2(Map<String, Double> mapValue, List<AttributeGroup> listAttrGroup, List<Venture> ventures) {
       
        final DefaultCategoryDataset dataset = new DefaultCategoryDataset();        
        for (AttributeGroup attrGroup : listAttrGroup) {
            for (Venture venture : ventures) {
                Double value = mapValue.get(attrGroup.getAttributeGroupName() +"---"+venture.getVentureName());
                dataset.addValue(value, attrGroup.getAttributeGroupName(), venture.getVentureName());
            }
        }
//        for (String groupName : mapValue.keySet()) {
//            Map<String,Long> mapVentureValue = mapValue.get(groupName);
//            for (String venture : mapVentureValue.keySet()) {
//                Long value = mapVentureValue.get(venture);
//                dataset.addValue(value, groupName, venture);
//            }
//        }
        
        return dataset;
                
    }
    
    private JFreeChart createChart(final CategoryDataset dataset) {
        
        // create the chart...
        final JFreeChart chart = ChartFactory.createLineChart(
            "Summary Quality Score - "+scorecardType.getType(),       // chart title
            "Week",                    // domain axis label
            "",                   // range axis label
            dataset,                   // data
                PlotOrientation.VERTICAL,  // orientation
            true,                      // include legend
            true,                      // tooltips
            false                      // urls
        );

        // NOW DO SOME OPTIONAL CUSTOMISATION OF THE CHART...
//        final StandardLegend legend = (StandardLegend) chart.getLegend();
  //      legend.setDisplaySeriesShapes(true);
    //    legend.setShapeScaleX(1.5);
      //  legend.setShapeScaleY(1.5);
        //legend.setDisplaySeriesLines(true);

        chart.setBackgroundPaint(Color.white);

        final CategoryPlot plot = (CategoryPlot) chart.getPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setRangeGridlinePaint(Color.white);

        // customise the range axis...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        rangeAxis.setAutoRangeIncludesZero(true);

        
        
        // customise the renderer...
        final LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
//        renderer.setDrawShapes(true);

//        renderer.setSeriesStroke(
//            0, new BasicStroke(
//                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
//                1.0f, new float[] {10.0f, 6.0f}, 0.0f
//            )
//        );
//        renderer.setSeriesStroke(
//            1, new BasicStroke(
//                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
//                1.0f, new float[] {6.0f, 6.0f}, 0.0f
//            )
//        );
//        renderer.setSeriesStroke(
//            3, new BasicStroke(
//                2.0f, BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND,
//                1.0f, new float[] {2.0f, 6.0f}, 0.0f
//            )
//        );
        //renderer.setSeriesLinesVisible(0, false);
       // renderer.setSeriesShapesVisible(1, false);
        plot.setRenderer(renderer);        
        
        return chart;
    }
    
    private JFreeChart createChart2(final CategoryDataset dataset) {
        int week = DateUtils.getCurrentWeekOfYear();
        // create the chart...
        final JFreeChart chart = ChartFactory.createBarChart(
            scorecardType.getType()+", week "+(week - 1),         // chart title
            "",               // domain axis label
            "",                  // range axis label
            dataset,                  // data
            PlotOrientation.VERTICAL, // orientation
            true,                     // include legend
            true,                     // tooltips?
            false                     // URLs?
        );
        
        // set the background color for the chart...
        chart.setBackgroundPaint(Color.white);

        // get a reference to the plot for further customisation...
        final CategoryPlot plot = chart.getCategoryPlot();
        plot.setBackgroundPaint(Color.lightGray);
        plot.setDomainGridlinePaint(Color.white);
        plot.setRangeGridlinePaint(Color.white);

        // set the range axis to display integers only...
        final NumberAxis rangeAxis = (NumberAxis) plot.getRangeAxis();
        rangeAxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());

        // disable bar outlines...
        final BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setDrawBarOutline(false);                

        final CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setCategoryLabelPositions(
                CategoryLabelPositions.createUpRotationLabelPositions(Math.PI / 6.0)
        );        
        
        return chart;
        
    }
}
